package com.yaoxun.bored.service.sys.dict;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yaoxun.bored.common.BaseService;
import com.yaoxun.bored.mapper.sys.dict.DictItemMapper;
import com.yaoxun.bored.mapper.sys.dict.DictMapper;
import com.yaoxun.bored.model.sys.dict.Dict;
import com.yaoxun.bored.model.sys.dict.DictItem;

import tk.mybatis.mapper.entity.Example;

@Service
public class DictService extends BaseService<Dict> {
	
	@Inject
	private DictMapper dictMapper;
	
	@Inject
	private DictItemMapper dictItemMapper;
	
	
	public int delete(Integer[] dictIds) {
		//删除dict
		Example example = new Example(Dict.class);
		List<Integer> values = Arrays.asList(dictIds);
		example.createCriteria().andIn("dictId", values);
		int dictCount = dictMapper.deleteByExample(example);
		//删除dictItem
		example = new Example(DictItem.class);
		example.createCriteria().andIn("dictId", values);
		dictItemMapper.deleteByExample(example);
		return dictCount;
	}
	
	/**
	 * 查询出所有的字典和字典项的关联关系
	 * @author Loren
	 * @createTime 2018年2月5日 上午9:11:18
	 * @return
	 */
	@Transactional(readOnly=true)
	@Cacheable(cacheNames={"dictsJson"}, key="'dictsSelectAllUseJs'")
	public Map<String, Object> selectAllUseJs() {
		Map<String, Object> map = new HashMap<>();
		List<Dict> dicts = dictMapper.selectUseinJs();
		for(Dict dict : dicts) {
			List<DictItem> dictItems = dictItemMapper.selectToJS(dict.getDictId());
			if(CollectionUtils.isNotEmpty(dictItems)) {				
				map.put(dict.getDictCode(), dictItems);
			}
		}
		return map;
	}
	
}
